package cn.mabach.goods.service.impl;


import cn.mabach.goods.dao.SkuStockDao;
import cn.mabach.goods.entity.SkuStockEntity;
import cn.mabach.goods.service.SkuStockService;
import cn.mabach.result.PageResult;
import cn.mabach.result.RS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class SkuStockServiceImpl extends ServiceImpl<SkuStockDao, SkuStockEntity> implements SkuStockService {

    @Override
    public RS<PageResult<SkuStockEntity>> queryPage(@RequestParam(value = "keyword", required = false) String keyword,
                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        if (pageSize>20){
            return RS.error("SkuStockServiceImpl非法参数");
        }
        IPage<SkuStockEntity> page = this.page(
                new Page<SkuStockEntity>(pageNum,pageSize),
                new QueryWrapper<SkuStockEntity>().like(!StringUtils.isEmpty(keyword),"name",keyword)
        );

        return RS.ok(new PageResult(page));
    }





    @Override
    public RS<SkuStockEntity> getByIdE(@RequestParam("id") Long id) {
            SkuStockEntity res = this.getById(id);

        return RS.ok(res);
    }

    @Override
    public RS saveE(@RequestBody  SkuStockEntity entity) {
        boolean b = this.save(entity);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    @Override
    public RS updateByIdE(@RequestBody SkuStockEntity entity) {
        boolean b = this.updateById(entity);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }



/*
* 根据商品编号及编码模糊搜索sku库存
* */

    public RS<List<SkuStockEntity>> getList(@RequestParam("pid") Long pid, @RequestParam(value = "keyword",required = false) String keyword) {

        List<SkuStockEntity> list = this.list(new QueryWrapper<SkuStockEntity>().eq("product_id", pid)
                .like(!StringUtils.isEmpty(keyword), "sku_code", keyword));


        return RS.ok(list);

    }

/*
* 批量更新库存信息
* */

    @Transactional
    public RS update(@RequestParam("pid") Long pid,@RequestBody List<SkuStockEntity> skuStockList){

        for (SkuStockEntity skuStockEntity : skuStockList) {

            skuStockEntity.setProductId(pid);
            boolean b = this.updateById(skuStockEntity);
            if (!b){
                return RS.error();
            }

        }
        return RS.ok();
}

}